<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { onMounted, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';
import { cloneDeep } from 'lodash-es';
import ExcelJS from 'exceljs';
import { useUpload } from './useUpload';
import { useDownExcel } from './useDownExcel';
import { useColumn } from './useColumn';
import details_add from './components/details_add.vue';
import useUserStore from '@/store/modules/user';
import { getDetailsByCompanyPage } from '@/api/modules/rbac/dcp/engineercertification_data';

const userStore = useUserStore();
const orgName = userStore.userOrgName;
const account = userStore.account;
const loading = ref<boolean>(false);
const searchKeyword = ref<string>('');
const data = ref<any[]>([]);
const total = ref<number>(0);
const pageSize = ref<number>(10);
const current = ref<number>(1);
const { columnsD } = useColumn();

function renderCellValue(record: { [x: string]: any }, dataIndex: string | number) {
  const value = record[dataIndex];
  switch (dataIndex) {
    case 'isRdCloud':
    case 'isRdBase':
    case 'isRdCommon':
    case 'isRdProfession':
      return value === 1 ? '是' : '否';
    default:
      return value;
  }
}

// 数据处理
const editableData: UnwrapRef<Record<string, any>> = reactive({});

// 获取所有人员明细数据;
async function fetchData() {
  loading.value = true;
  data.value = [];
  let allData: any[] = [];
  if (account === '管理员') {
    await getEngineerByPage(current.value, pageSize.value).then((response: any) => {
      total.value = response.data.total;
      allData = response.data.records;
    });
  }
  else {
    await getDetailsByCompanyPage(current.value, pageSize.value, orgName).then((response: any) => {
      total.value = response.data.total;
      allData = response.data.records;
    });
  }
  data.value = allData;
  loading.value = false;
}
provide('fetchData', fetchData);
async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  if (searchKeyword.value === '') {
    fetchData();
  }
}

onMounted(() => {
  fetchData();
});

// 查询功能
const codePattern = /^-?\d+(\.\d+)?$/;

async function onSearch(searchKeyword: any) {
  if (codePattern.test(searchKeyword)) {
    try {
      const response: any = await certificationsearch({ personnelCode: searchKeyword });
      data.value = response.data;
      total.value = response.data.length;
      if (total.value === 0) {
        message.success('没有查询到相关记录');
      }
      else {
        message.success('查询成功');
      }
    }
    catch (error) {
      console.error('按编码查询失败:', error);
    }
  }
  else {
    try {
      if (searchKeyword === '') {
        const response: any = await certificationsearch({});
        data.value = response.data;
        total.value = response.data.length;
      }
      else {
        const response: any = await certificationsearch({ name: searchKeyword });
        data.value = response.data;
        total.value = response.data.length;
        if (total.value === 0) {
          message.success('没有查询到相关记录');
        }
        else {
          message.success('查询成功');
        }
      }
    }
    catch (error) {
      console.error('按姓名查询失败:', error);
    }
  }
}

// 删除功能
async function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      deleteSingleRecord([id]);
    },
  });
}

async function deleteSingleRecord(id: number[]) {
  try {
    await certificationdeleteids(id);
    message.success('记录删除成功');
  }
  catch (error) {
    message.error('删除失败');
  }
}

// 编辑功能
function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  const updateDate = {
    id: newData.id,
    company: newData.company,
    name: newData.name,
    personnelCode: newData.personnelCode,
    isRdCloud: newData.isRdCloud,
    isRdBase: newData.isRdBase,
    isRdCommon: newData.isRdCommon,
    rdCommonLevel: newData.rdCommonLevel,
    isRdProfession: newData.isRdProfession,
    rdProfessionLevel: newData.rdProfessionLevel,
    rdExperienceLevel: newData.rdExperienceLevel,
    experience: newData.experience,
  };
  await certificationupdate(updateDate).then(() => {
    message.success('修改成功');
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            const worksheet: any = workbook.getWorksheet(1);
            const headers: any[] = [];
            const flag = useUpload().checkDetailsHeader(worksheet, headers);
            if (flag) {
              await certificationFileupload(formData).then(() => {
                message.success('上传成功！');
                handleRemove(file);
                fetchData();
              })
                .catch(() => {
                  message.error('上传失败');
                  fetchData();
                });
            }
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 选中
const selectedId = ref<number[]>([]);

function clearSelected() {
  selectedId.value = [];
}

const isSelected = computed(() => {
  return selectedId.value.length > 0;
});

// 全选功能
let flag = true;
function selectAll() {
  if (flag) {
    const allIds = data.value.map((item: { id: any }) => item.id);
    selectedId.value = allIds;
    flag = !flag;
  }
  else {
    selectedId.value = [];
    flag = !flag;
  }
}

// 批量删除
async function clearChoose(selectedId: number[]) {
  loading.value = true;
  try {
    const res: any = await certificationdeleteids(selectedId);
    if (res) {
      message.success('删除成功');
      fetchData();
      clearSelected();
    }
  }
  catch (error) {
    message.error('删除失败');
  }
  finally {
    loading.value = false;
  }
}

const { auth } = useAuth();

function handleSelectionChange(selectedRowKeys: any[]) {
  selectedId.value = selectedRowKeys;
}
// 新增
const visible = ref<boolean>(false);
function showDrawer() {
  visible.value = !visible.value;
}
</script>

<template>
  <div py-10px px-10px w-full h-full>
    <PubPageMain class="max" auto-height :scroll="{ x: 1100 }">
      <div class="header">
        <div class="left">
          <a-space>
            <div class="pjTitle">
              研发人员明细
            </div>
            <a-button v-auth="'e-details-edit'" type="link" @click="selectAll">
              全选
            </a-button>
            <a-button v-auth="'e-details-edit'" type="link" @click="showDrawer">
              新增
            </a-button>
            <a-input-search
              v-model="searchKeyword" v-auth="'e-details-search'" placeholder="请输入完整的人员编码或姓名" enter-button
              style="width: 260px;" @search="onSearch"
            />
          </a-space>
        </div>
        <div class="right">
          <a-space>
            <a-button v-if="isSelected" v-auth="'e-details-edit'" type="primary" @click="clearChoose(selectedId)">
              批量删除
            </a-button>
            <a-upload
              v-auth="'e-details-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
              :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
            >
              <a-button>
                <upload-outlined /> 点击选择文件
              </a-button>
            </a-upload>
            <a-button v-auth="'e-details-upload'" type="primary" @click="handleManualUpload">
              上传
            </a-button>
            <a-button v-auth="'e-details-upload'" type="primary" @click="useDownExcel().downDetailsExcel">
              下载模板
            </a-button>
          </a-space>
        </div>
      </div>
      <details_add :visible="visible" :get-visible="showDrawer" />
      <div class="content">
        <a-table
          :columns="columnsD" :data-source="data" row-key="id" class="d-table" :scroll="{ x: 1500 }"
          :row-selection="{ selectedRowKeys: selectedId, onChange: handleSelectionChange, getCheckboxProps: () => ({ disabled: !auth(['e-details-edit']) }) }"
          :loading="loading" :pagination="{ pageSize, showQuickJumper: true, total }" @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template
              v-if="['company', 'name', 'isRdCloud', 'isRdBase', 'isRdCommon', 'rdCommonLevel', 'isRdProfession', 'rdProfessionLevel', 'rdExperienceLevel', 'experience'].includes(column.dataIndex as string)"
            >
              <div>
                <a-input
                  v-if="editableData[record.id]"
                  v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
                />
                <template v-else>
                  {{ renderCellValue(record, column.dataIndex as any) }}
                </template>
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a-typography-link @click="save(record.id)">保存</a-typography-link>
                  <a @click="cancel(record.id)">取消</a>
                </span>
                <span v-else>
                  <a-space>
                    <a @click="edit(record.id)">编辑</a>
                    <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                  </a-space>
                </span>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </PubPageMain>
  </div>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .editable-row-operations a {
    margin-right: 8px;
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .d-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}
</style>
